/***************************************************************************
 *   Copyright (C) 2008 by Marco Gulino   *
 *   marco.gulino@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor Boston, MA 02110-1301, USA            *
 ***************************************************************************/
#include "fileutils.h"
#include <QDir>
#include <QDirIterator>
#include <QDebug>
#include <QFile>
#include <QTextStream>

void FileUtils::rmDir(const QString &path)
{
    QDirIterator it(path, QDir::Files, QDirIterator::Subdirectories);
    while( it.hasNext() )
        QFile::remove(it.next());

    int tries=0;
    QDir current(path);
    while (current.entryList().size() > 0 && tries < 10) {
        tries++;
        QDirIterator dirs(path, QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
        while( dirs.hasNext() ) {
            current.rmpath(dirs.next() );
        }
    }
    current.rmdir(path);
}

void FileUtils::cleanWorkDir() {
    rmDir(WORKDIR);
    QDir().mkdir(WORKDIR);
}

void FileUtils::fileOf(long kilobytes, const QString &path)
{
    fileOf(kilobytes, 1024, path, '0');
}

void FileUtils::fileWith(const QString &pattern, int repeat, const QString &path) {
    QFile out(path);
    out.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream stream(&out);
    for(int i=0; i< repeat; i++)
        stream << pattern;
    out.close();
}


void FileUtils::fileOf(long size, long multiplier, const QString &path, const QChar &fill)
{
    QString fillString(multiplier, fill);
    fileWith(fillString, size, path);
}
